package com.getan.boot.module.system.controller;

import com.getan.boot.common.Pagination;
import com.getan.boot.common.ResponseBuilder;
import com.getan.boot.common.ResponseCodeData;
import com.getan.boot.common.annotation.OperateLog;
import com.getan.boot.common.domain.bo.IdsBO;
import com.getan.boot.jdbc.customquery.CustomQueryBO;
import com.getan.boot.module.system.domain.bo.ConfigBO;
import com.getan.boot.module.system.entity.ConfigEntity;
import com.getan.boot.module.system.service.persistent.ConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 部门管理
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/config")
public class ConfigController {

    private final String MODULE = "配置管理";
    private final ConfigService configService;

    @PostMapping("search")
    public ResponseCodeData<Pagination<ConfigEntity>> search(@RequestBody @Valid CustomQueryBO bo) {
        return ResponseBuilder.ok(configService.page(bo));
    }

    @OperateLog(module = MODULE, businessType = "ADD")
    @PostMapping("add")
    public ResponseCodeData<Long> add(@RequestBody @Valid ConfigBO.AddBO bo) {
        ConfigEntity entity = new ConfigEntity();
        BeanUtils.copyProperties(bo, entity);
        configService.checkCode(entity);
        entity.setSys(false);
        configService.insert(entity);
        configService.removeCache();
        return ResponseBuilder.ok(entity.getId());
    }

    @OperateLog(module = MODULE, businessType = "UPDATE")
    @PostMapping("update")
    public ResponseCodeData<Long> update(@RequestBody @Valid ConfigBO.UpdateBO bo) {
        ConfigEntity entity = new ConfigEntity();
        BeanUtils.copyProperties(bo, entity);
        configService.canUpdate(bo.getId());
        configService.update(entity);
        configService.removeCache();
        return ResponseBuilder.ok(entity.getId());
    }

    @OperateLog(module = MODULE, businessType = "DELETE")
    @PostMapping("delete")
    public ResponseCodeData<Void> delete(@RequestBody @Valid IdsBO bo) {
        configService.canDelete(bo.getIds());
        configService.deleteBatch(bo.getIds());
        configService.removeCache();
        return ResponseBuilder.ok();
    }

}
